import json

import pymysql
import configparser
import requests
import time
from collections import defaultdict
from flask import Flask
from flask.globals import request
from Crypto.Cipher import AES
import base64, hashlib, os


def get_access_token(corpid, corpsecret):
    try:
        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}"
        response = requests.get(url)
        data = response.json()

        if 'access_token' in data:
            access_token = data['access_token']
            expires_in = data['expires_in']
            expiration_time = time.time() + expires_in - 60  # 提前一分钟过期

            # 将 access_token 和 过期时间存储下来，这里使用简单的文件存储
            with open('access_token.txt', 'w') as f:
                f.write(f"{access_token}\n{expiration_time}")
            return access_token, expiration_time

    except Exception as e:
        print(f"Failed to get access token: {e}")

    return None, 0


def check_access_token(CORP_ID, CORP_SECRET):
    try:
        with open('access_token.txt', 'r') as f:
            data = f.read().splitlines()
            access_token = data[0]
            expiration_time = float(data[1])

            if time.time() < expiration_time:
                return access_token
            else:
                print("Access token expired. Refreshing...")
                return get_access_token(CORP_ID, CORP_SECRET)[0]
    except Exception as e:
        print(f"Failed to read access token file: {e}")

    return None


# 用于记录不同操作的调用次数
call_count = defaultdict(int)
last_call_time = defaultdict(float)


def check_frequency(operation, limit, interval):
    current_time = time.time()
    if current_time - last_call_time[operation] < interval:
        call_count[operation] += 1
        if call_count[operation] > limit:
            print(f"Exceeded frequency limit for operation: {operation}")
            return False
    else:
        call_count[operation] = 1

    last_call_time[operation] = current_time
    return True


def sendMsg(access_token, userid, message,agentid):
    if not check_frequency('sendMsg', 20000, 60):  # 检查基础频率限制
        return None

    url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}&debug=1"
    data = {
        "touser": userid,
        "msgtype": "text",
        "agentid": agentid,
        "text": {
            "content": message
        }
    }
    try:
        response = requests.post(url, json=data)
        result = response.json()
        return result
    except Exception as e:
        print(f"Failed to send linkedcorp message: {e}")
        return None


def getUserid(access_token, phone):
    url = f"https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token={access_token}"
    data = {
        "mobile": phone
    }
    try:
        response = requests.post(url, json=data)
        result = response.json()
        return result
    except Exception as e:
        print(f"Failed to send linkedcorp message: {e}")
        return None


# 使用方法
if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read('config.ini')
    CORP_ID = config['wx']['CORP_ID']
    CORP_SECRET = config['wx']['CORP_SECRET']
    agentid = config['wx']['agentid']
    token = check_access_token(CORP_ID, CORP_SECRET)
    if not token:
        token = get_access_token(CORP_ID, CORP_SECRET)[0]
    print(f'获取token是{token}')
    # 从配置文件读取数据库连接信息和SQL查询

    host = config['DATABASE']['host']
    user = config['DATABASE']['user']
    port = config['DATABASE'].getint('port', 3306)  # 设置默认端口为 3306
    password = config['DATABASE']['password']
    database = config['DATABASE']['database']
    sql_query = config['SQL']['query']

    print(f"Connecting to MySQL database at {host}:{port} as user {user}...")

    # 连接数据库
    connection = pymysql.connect(host=host, port=port, user=user, password=password, database=database)
    cursor = connection.cursor()

    print("Executing SQL query...")

    # 执行SQL查询
    cursor.execute(sql_query)
    results = cursor.fetchall()

    # 输出查询结果
    if results:
        for row in results:
            phone = row[0]
            message = row[1]
            print(f'发送用户:{phone},消息:{message}')
            userresult = getUserid(token, phone)
            if userresult['errcode'] == 0:
                userid = userresult['userid']
                print(f'手机号查询企业微信userid:{userid}')
                result = sendMsg(token, userid, message,agentid)
                if results is None:
                    print('发送频率过于频繁！发送失败')
                else:
                    print(f'发送结果：{result}')
            else:
                print(f'用户{phone}不在企业微信')
    else:
        print("No results found for the query.")

    # 关闭数据库连接
    connection.close()

    print("Database connection closed.")
